package elitech.vietnam.weatherfashion.tabs.styler;

import java.io.IOException;
import java.util.List;

import android.os.AsyncTask;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshBase.Mode;
import com.handmark.pulltorefresh.library.PullToRefreshBase.OnRefreshListener2;
import com.handmark.pulltorefresh.library.PullToRefreshGridView2;
import com.koushikdutta.urlimageviewhelper.UrlImageViewHelper;

import elitech.vietnam.weatherfashion.R;
import elitech.vietnam.weatherfashion.WFApplication;
import elitech.vietnam.weatherfashion.backgroundtask.ButtonAskFriendTask;
import elitech.vietnam.weatherfashion.config.Const;
import elitech.vietnam.weatherfashion.config.GlobalValue;
import elitech.vietnam.weatherfashion.config.Utils;
import elitech.vietnam.weatherfashion.custom.dialogues.DialogUserInfo;
import elitech.vietnam.weatherfashion.custom.dialogues.PicPickerDialog;
import elitech.vietnam.weatherfashion.custom.dialogues.TimeOutDialog;
import elitech.vietnam.weatherfashion.custom.multicolumnlistview.MultiColumnListView;
import elitech.vietnam.weatherfashion.dto.MemberDTO;
import elitech.vietnam.weatherfashion.dto.PostDTO;
import elitech.vietnam.weatherfashion.service.PHPSoapServiceCaller;
import elitech.vietnam.weatherfashion.tabs.AbstractFragment;

public class StylerDetailFragment extends AbstractFragment implements View.OnClickListener, OnRefreshListener2<MultiColumnListView> {

	private PostDTO post;
	private MemberDTO member;
	private int memId = -1;
	private List<PostDTO> posts;
	private ProgressBar progress_addfriend;
	private TextView text_username, text_userstatus;
	private ImageView image_useravatar, image_addfriend;
	private PullToRefreshGridView2 gridview_main;
	private StylerDetailGridAdapter mAdapter;
	private Button button_camera;

	boolean isPullUp = false;
	
	public static StylerDetailFragment init(PostDTO post) {
		StylerDetailFragment fr = new StylerDetailFragment();
		fr.post = post;
		return fr;
	}

	public static StylerDetailFragment init(int memId) {
		StylerDetailFragment fr = new StylerDetailFragment();
		fr.memId = memId;
		return fr;
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
		View view = inflater.inflate(R.layout.tab_stylerdetail, container, false);
		setupView(view);

		progress_addfriend = (ProgressBar) view.findViewById(R.id.meminfo_addfriend_progress);
		image_addfriend = (ImageView) view.findViewById(R.id.meminfo_button_addfriend);
		text_username = (TextView) view.findViewById(R.id.meminfo_textview_username);
		text_userstatus = (TextView) view.findViewById(R.id.meminfo_textview_userstatus);
		image_useravatar = (ImageView) view.findViewById(R.id.meminfo_image_useravatar);
		gridview_main = (PullToRefreshGridView2) view.findViewById(R.id.layout_main);
		button_camera = (Button) view.findViewById(R.id.styler_button_camera);

		if (!isAdded())
			return null;

		button_camera.setOnClickListener(this);

		// if (member == null || posts == null || posts.isEmpty())
		// new StylerDetailLoadingTask().execute();
		// else {
		// loadMember();
		// loadPost();
		// loadButtonFriend();
		// }

		if ((posts == null || posts.isEmpty()))
			new GetStylerPostTask().execute();
		else
			loadPost();
		if (member == null)
			new GetMemberTask().execute();
		else {
			loadMember();
			loadButtonFriend();
		}
		return view;
	}
	
	@Override
	public void onPause() {
		super.onPause();
		gridview_main.onRefreshComplete();
	}

	@Override
	public void onDestroyView() {
		gridview_main = null;
		mAdapter = null;
		posts = null;
		member = null;
		super.onDestroyView();
	}

	public void loadPost() {
		if (gridview_main == null)
			return;
		if (posts.isEmpty()) {
			onNoData(true);
			return;
		}
		mAdapter = new StylerDetailGridAdapter(this, member, R.layout.styler_grid_item, posts);
		gridview_main.setMode(Mode.PULL_FROM_END);
		gridview_main.setOnRefreshListener(this);
		gridview_main.setAdapter(mAdapter);
	}

	public void loadMember() {
		if (member == null)
			return;
		// ImageLoader.getInstance().displayImage(AppConfig.SERVER_IMAGE_URL +
		// this.member.getMemberPic(), image_useravatar);
		UrlImageViewHelper.setUrlDrawable(image_useravatar, Const.SERVER_IMAGE_URL + this.member.getMemberPic(), R.drawable.no_avatar);
		text_username.setText(this.member.getMemberName());
		text_userstatus.setText(this.member.getMemberProfile());
		image_useravatar.setOnClickListener(this);
	}

	public void loadButtonFriend() {
		MemberDTO user = GlobalValue.getInstance(getActivity()).readUserInfo();
		if (member == null || WFApplication.getInstance().userFriends == null || user == null)
			return;
		if (member.getId() == user.getId())
			return;
		if (Utils.isFriend(member.getId())) {
			image_addfriend.setImageResource(R.drawable.icon_friended);
		} else {
			image_addfriend.setImageResource(R.drawable.icon_addfriend);
			image_addfriend.setOnClickListener(this);
		}
	}

	@Override
	public void onClick(View v) {
		MemberDTO user = GlobalValue.getInstance(getActivity()).readUserInfo();
		switch (v.getId()) {
		case R.id.meminfo_button_addfriend:
			new ButtonAskFriendTask(getActivity(), image_addfriend, progress_addfriend).execute(user.getId(), member.getId());
			break;

		case R.id.styler_button_camera:
			if (user == null) {
				Utils.openLogin(getActivity());
			} else
				new PicPickerDialog(getActivity(), this).show();
			break;

		case R.id.meminfo_image_useravatar:
			new DialogUserInfo(getActivity(), member).show();
			break;

		default:
			break;
		}
	}

	//
	// class StylerDetailLoadingTask extends AsyncTask<Integer, Integer,
	// Boolean> {
	// @Override
	// protected Boolean doInBackground(Integer... params) {
	// PHPSoapServiceCaller appService = new PHPSoapServiceCaller();
	// member = appService.getInfoMember(post.getStoreId());
	// posts = appService.getFashionMemberLike(post.getStoreId());
	// return null;
	// }
	//
	// @Override
	// protected void onPreExecute() {
	// super.onPreExecute();
	// onLoading(true);
	// }
	//
	// @Override
	// protected void onPostExecute(Boolean result) {
	// super.onPostExecute(result);
	// if (!isAdded())
	// return;
	// onLoading(false);
	// loadMember();
	// loadPost();
	// loadButtonFriend();
	// }
	// }

	class GetStylerPostTask extends AsyncTask<Integer, Integer, Boolean> {
		@Override
		protected Boolean doInBackground(Integer... params) {
			PHPSoapServiceCaller appService = new PHPSoapServiceCaller();
			MemberDTO user = GlobalValue.getInstance(getActivity()).readUserInfo();
			int myId = user == null ? -1 : user.getId();
			int n = post != null ? post.getStoreId() : memId;
			// if (AppConfig.getInstance().appUser != null)
			// try {
			// posts = appService.getFashionMemberLikeCountry(post.getStoreId(),
			// myId, AppConfig.getInstance().appUser.getMemberArea());
			// } catch (IOException e) {
			// return false;
			// }
			// else
			try {
				posts = appService.getFashionMemberLikeCountry(n, myId, Const.COUNTRY_CODE, 0, Const.LOADMORE_PAGE_ITEMCOUNT);
			} catch (IOException e) {
				return false;
			}
			return null;
		}

		@Override
		protected void onPostExecute(Boolean result) {
			super.onPostExecute(result);
			if (!isAdded())
				return;
			onLoading(false);
			if (result != null) {
				new TimeOutDialog(getActivity()).show();
				return;
			}
			loadPost();
			if (member != null)
				loadMember();
		}

		@Override
		protected void onPreExecute() {
			super.onPreExecute();
			if (!isAdded())
				return;
			onLoading(true);
		}
	}

	class GetMemberTask extends AsyncTask<Integer, Integer, Boolean> {
		@Override
		protected Boolean doInBackground(Integer... params) {
			PHPSoapServiceCaller appService = new PHPSoapServiceCaller();
			int n = post != null ? post.getStoreId() : memId;
			try {
				member = appService.getInfoMember(n);
			} catch (IOException e) {
				return false;
			}
			return null;
		}

		@Override
		protected void onPostExecute(Boolean result) {
			super.onPostExecute(result);
			if (!isAdded())
				return;
			if (result != null) {
				new TimeOutDialog(getActivity()).show();
				return;
			}
			loadMember();
			loadButtonFriend();
			if (posts != null)
				loadPost();
		}
	}

	@Override
	public void onPullDownToRefresh(PullToRefreshBase<MultiColumnListView> refreshView) {
		new LoadMoreItem().execute();
	}

	@Override
	public void onPullUpToRefresh(PullToRefreshBase<MultiColumnListView> refreshView) {
		new LoadMoreItem().execute();
	}
	
	class LoadMoreItem extends AsyncTask<Integer, Integer, List<PostDTO>> {
		@Override
		protected List<PostDTO> doInBackground(Integer... params) {
			PHPSoapServiceCaller service = new PHPSoapServiceCaller();
			MemberDTO user = GlobalValue.getInstance(getActivity()).readUserInfo();
			int n = (user != null) ? user.getId() : -1;
			int m = post != null ? post.getStoreId() : memId;
			List<PostDTO> list = null;
			try {
				list = service.getFashionMemberLikeCountry(m, n, Const.COUNTRY_CODE, posts.size(), Const.LOADMORE_PAGE_ITEMCOUNT);
			} catch (IOException e) {
				e.printStackTrace();
				return null;
			}
			return list;
		}
		@Override
		protected void onPreExecute() {
			super.onPreExecute();
		}
		@Override
		protected void onPostExecute(List<PostDTO> result) {
			super.onPostExecute(result);
			if (gridview_main != null)
				gridview_main.onRefreshComplete();
			if (result == null) {
				new TimeOutDialog(getActivity()).show();
				return;
			}
			if (result.isEmpty()) {
				if (gridview_main != null) {
					gridview_main.setMode(Mode.DISABLED);
					gridview_main.setOnRefreshListener((OnRefreshListener2<MultiColumnListView>)null);
				}
				return;
			}
			if (posts != null)
				posts.addAll(result);
			if (mAdapter != null)
				mAdapter.notifyDataSetChanged();
		}
	}
}
